<template>
    <div>
        <el-form :model="formdata" label-width="auto">
            <el-row class="">
                <el-col :span="8" class="">
                    <el-form-item label="查询用户">
                        <el-input v-model="formdata.userid" placeholder="请输入用户ID" class="input-with-select" clearable>
                            <template #append>
                                <el-button @click="" :icon="Search" />
                            </template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="10" class="margin-left20">
                    <el-form-item>
                        <el-button @click="excel()" type="primary">导出Excel</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row class="">
                <el-col :span="8" class="">
                    <el-form-item label="添加用户">
                        <el-select v-model="user" filterable remote reserve-keyword placeholder="请输入用户D、手机或用户名"
                            :remote-method="remoteMethod" :loading="loading" clearable>
                            <el-option v-for="item in users" :key="item.ID" :label="item.name" :value="item.ID" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="10" class="margin-left20">
                    <el-button :disabled="!user" @click="add" type="primary">添加</el-button>
                </el-col>
            </el-row>
        </el-form>

        <div class="row mb-1">
            <div class="col">
                <el-table border :data="useractivity" height="68vh" style="width: 100%">
                    <el-table-column prop="userid" label="用户ID"></el-table-column>
                    <el-table-column prop="user.name" label="用户名"></el-table-column>
                    <el-table-column prop="updatedAt" :formatter="({ createdAt }) => toLocaleDateString(createdAt)"
                        label="报名时间"></el-table-column>
                    <el-table-column prop="updatedAt" label="删除">
                        <template #default="scope">

                            <el-button type="danger" @click="del(scope.row.ID)" size="default">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>

        <el-pagination class="pager" :page-sizes="[20, 100, 50, 200, 300, 400, count]"
            @current-change="handleCurrentChange" @size-change="handleSizeChange" :page-size="Number(formdata._limit)"
            layout="total, sizes, prev, pager, next, jumper" :total="count"></el-pagination>

    </div>
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, reactive, ref, watch } from 'vue';
import { Iobj, asyncaddactivityuser, asyncdelactivityuser, asyncselectactivityuser, asyncselectuser } from '../../../api';
import Studycodemodel from '../../../mysql_interface/studycodemodel';
import { getExceltodownload } from '../../../util/excel';
import { toLocaleDateString } from '../../../util/time';

const p = defineProps<{ data: Studycodemodel.Iactivity }>()
const user = ref<number>()
const users = ref<Studycodemodel.Iuser[]>([])
const loading = ref(false)

const useractivity = ref<Studycodemodel.Iactivityuser[]>([])

const count = ref(0)

const remoteMethod = (query: string) => {
    if (query) {
        loading.value = true
        asyncselectuser({
            _like: [
                ['ID', query],
                ['name', query],
                ['phonenum', query],
                ['gid', query],
            ]
        }).then(e => {
            loading.value = false
            const { rows } = e
            users.value = rows
        })
    }
}

function handleCurrentChange(val: number) {
    formdata._offset = Number(formdata._limit) * (val - 1);
}

const formdata = reactive<Iobj<Studycodemodel.Iactivityuser>>({
    _limit: 20,
    _offset: 0,

})

onMounted(() => {
    start()
})

watch(formdata, start)

async function start() {
    formdata.activityid = p.data.ID
    const data = await asyncselectactivityuser(formdata)
    useractivity.value = data.rows
    count.value = data.count

}

function handleSizeChange(val: number) {
    formdata._limit = val
}

function excel() {
    const act: (string | number | undefined)[][] = [
        ["用户id", "用户名称", "比赛名称", "报名时间", "qq", "微信opendid"],
    ];
    let __activityname;
    const _act = useractivity.value.map((v) => {
        const { userid, createdAt = "", user } = v;
        let qq, openid;
        if (user) {
            qq = user.qq;
            openid = user.openid;
        }
        __activityname = p.data.name;
        return [
            userid,
            v.user?.name,
            p.data.name,
            toLocaleDateString(createdAt),
            qq,
            openid,
        ];
    });

    getExceltodownload(act.concat(_act), `${__activityname}比赛成绩表`);

}
function del(ID: number) {
    try {
        ElMessageBox.confirm("取消此用户报名, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        })
            .then(async () => {
                await asyncdelactivityuser({ ID });
                ElMessage({
                    type: "success",
                    message: "删除成功!",
                });
                start();
            })
            .catch(() => {
                ElMessage({
                    type: "info",
                    message: "已取消删除",
                });
            });
    } catch (e: any) {
        ElMessage({
            message: "删除失败" + e,
            type: "error",
        });
    }
}


async function add() {
    await asyncaddactivityuser({
        userid: user.value,
        activityid: p.data.ID
    })
    ElMessage.success('添加成功')
    start()
}

</script>